#!/usr/bin/env bash
set -eo pipefail

base_path=$(pwd)
types="java"

usage() {
  echo "Usage:"
  echo "  $0 [-a absolute_dir] [-b base_dir] [-s sub_dir] [-t file_types] [-h]"
  echo "    -a absolute_dir (absolute path)"
  echo "    -b base_dir (relative to current dir)"
  echo "    -s sub_dir (relative to base_dir)"
  echo "    -t file_types (comma separated, e.g. java,py,cpp)"
  echo "    -h show help"
  exit 1
}

# 参数解析
while [[ $# -gt 0 ]]; do
  case "$1" in
    -a)
      if [[ -z "$2" ]]; then usage; fi
      base_path="$2"
      shift 2
      ;;
    -b)
      if [[ -z "$2" ]]; then usage; fi
      base_path="$(pwd)/$2"
      shift 2
      ;;
    -s)
      if [[ -z "$2" ]]; then usage; fi
      base_path="$base_path/$2"
      shift 2
      ;;
    -t)
      if [[ -z "$2" ]]; then usage; fi
      types="$2"
      shift 2
      ;;
    -h)
      usage
      ;;
    *)
      echo "Unknown argument: $1"
      usage
      ;;
  esac
done

# 将逗号替换为空格，方便遍历
types="${types//,/ }"

total=0

for ext in $types; do
  # 查找所有匹配文件，统计行数
  count=$(find "$base_path" -type f -name "*.$ext" -exec cat {} + | wc -l || echo 0)
  echo "$ext code lines: $count"
  total=$((total + count))
done
echo "total code lines: $total"
